package com.tom.mqconsumer;

import com.rabbitmq.client.Channel;
import com.tom.config.RabbitMQConfig;
import com.tom.to.PrepareOrderTo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

//消费死亡队列中的消息
@Component
@Slf4j
public class KillDeadMessgeConsumer  {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate ;

    @Autowired
    private RedissonClient redissonClient ;

    //监听死信队列消息
    @RabbitListener(queues = RabbitMQConfig.QUEUE_DEAD_KILL ,containerFactory = "rabbitListenerContainerFactory")
    public void deadMessgeHandler(String key, Message message , Channel channel){
        log.error("拿到过期消息 {}",key );
        //根据KEY获取到Redis中的预创订单
        PrepareOrderTo prepareOrderTo = (PrepareOrderTo) redisTemplate.opsForValue().get(key);
        if(prepareOrderTo != null){
            //如果不为空，说明还没有下单，因为下单后会删除Redis中的预创订单
            RSemaphore semaphore = redissonClient.getSemaphore("STORE_" + prepareOrderTo.getKillCourseId());
            //释放库存
            semaphore.release(1);
            redisTemplate.delete(key);
            log.error("下单超时，删除预创订单，退库存 {}",prepareOrderTo );
        }

        //签收消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
